package com.tjbklx1.redis.chap05;

import java.util.List;
import java.util.Set;

import com.tjbklx1.redis.JedisUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
import redis.clients.jedis.Tuple;

/**
 * 统计访问每个页面的时间
 * @author tjbklx1
 * @date 2018-12-6
 */
public class App55_AccessTime {

	public static void main(String[] args) throws Exception {
		Jedis conn = JedisUtil.getJedisWithDB();
		new App55_AccessTime().testAccessTime(conn);
	}

	public void testAccessTime(Jedis conn) throws InterruptedException {
		System.out.println("\n----- testAccessTime -----");
		System.out.println("Let's calculate some access times...");
		AccessTimer timer = new AccessTimer(conn);
		for (int i = 0; i < 10; i++) {
			timer.start();
			Thread.sleep((int) ((.5 + Math.random()) * 1000));
			timer.stop("req-" + i);
		}
		System.out.println("The slowest access times are:");
		Set<Tuple> atimes = conn.zrevrangeWithScores("slowest:AccessTime", 0, -1);
		for (Tuple tuple : atimes) {
			System.out.println("  " + tuple.getElement() + ", " + tuple.getScore());
		}
		assert atimes.size() >= 10;
		System.out.println();
	}

	public class AccessTimer {
		private Jedis conn;
		private long start;

		public AccessTimer(Jedis conn) {
			this.conn = conn;
		}

		public void start() {
			start = System.currentTimeMillis();
		}

		public void stop(String context) {
			long delta = System.currentTimeMillis() - start;
			// 更新统计信息
			List<Object> stats = new App54_LogStats().updateStats(conn, context, "AccessTime", delta / 1000.0);
			double average = (Double) stats.get(1) / (Double) stats.get(0);

			Transaction trans = conn.multi();
			trans.zadd("slowest:AccessTime", average, context);
			trans.zremrangeByRank("slowest:AccessTime", 0, -101); // 截取最后的100条数据
			trans.exec();
		}
	}
}
